package com.immortal.module.security;

import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author xukk
 */
@Slf4j
public class SecurityUtils {

    public static Authentication getSubject() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Object getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static SecUser getSecUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Preconditions.checkNotNull(authentication, "无法读取用户");
        Object o = authentication.getPrincipal();
        Preconditions.checkArgument(o instanceof SecUser, "无法读取用户");
        SecUser secUser = (SecUser) o;
        Preconditions.checkNotNull(secUser.getId(), "无法读取用户");
        return secUser;
    }

    public static SecUser getSecUserOrNo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication.getPrincipal() instanceof SecUser) {
                return (SecUser) authentication.getPrincipal();
            }
        }
        return null;

    }

    public static String getSecUserId() {
        SecUser secUser=getSecUser();
        String id = secUser.getId();
        Preconditions.checkNotNull(id, "无法读取用户");
        return id;
    }

    public static String getSecUserIdOrNo() {
        SecUser secUser=getSecUserOrNo();
        if(secUser!=null){
            return secUser.getId();
        }
        return null;
    }

}
